package controllers

import (
	// "bytes"
	"cybeego/models"
	"cybeego/myutils"
	"path"
	"reflect"
	"time"

	// "cybeego/redispool"
	// "encoding/gob"
	// "math"
	// "path"
	// "time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	// "github.com/gomodule/redigo/redis"
)

type DomainController struct {
	beego.Controller
}

func (c *DomainController) ActivateDomain() {

	id, err := c.GetInt("id")
	if err != nil {
		logs.Info("获取ID失败：", err)
		return
	}
	content := models.Domain{Id: id}
	o := orm.NewOrm()
	err = o.Read(&content)
	if err != nil {
		logs.Info("查询数据失败：", err)
		return
	}
	c.Data["username"] = c.GetSession("username")
	username := c.GetSession("username")
	if username != "admin" {
		c.TplName = ("fail.html")
	}
	// 发送邮件
	// Filter
	myuser := models.User{}
	qs := o.QueryTable("user")
	qs.Filter("Id", content.User.Id).One(&myuser)
	myutils.SendMail(myuser.Email, myuser.Name, "域名地址："+content.Title, content.Content+"激活成功")

	//
	content.Status = true
	// o.Update(content)
	// o.Insert(&content) //这里需要传递指针变量
	cid, cerr := o.Update(&content)
	if err != nil {
		logs.Error(" cid cerr ", cid, cerr)
		c.TplName = ("fail.html")
	}
	logs.Info(" update domian id content", content.Id, "staus修改为：", content.Status)
	c.TplName = ("success.html")

}

func (c *DomainController) ShowDomainList() {

	c.TplName = "domain_show.html"
	var domainsall []models.Domain
	var domains []models.Domain
	o := orm.NewOrm()

	sessionname := c.GetSession("username")
	// Filter
	uservalue := sessionname.(string)
	myuser := models.User{}
	qs := o.QueryTable("user")
	qs.Filter("Name", uservalue).One(&myuser)
	// 查询当前登录用户的域名
	o.QueryTable("domain").Filter("User", myuser.Id).All(&domains)
	// 查询域名项目列表
	// var domaintypes []models.DomainType
	// o.QueryTable("domain_type").All(&domaintypes)
	// c.Data["domaintypes"] = domaintypes
	// 查询用户
	// 前端变量
	o.QueryTable("domain").All(&domainsall) // 查询所有
	if uservalue == "admin" {
		c.Data["domains"] = domainsall
	} else {
		c.Data["domains"] = domains
	}

	c.Data["username"] = c.GetSession("username")
	c.Data["userid"] = c.GetSession("userid")
}

func (c *DomainController) ShowAddDomain() {

	//域名项目类型下拉
	o := orm.NewOrm()
	domaintypes := []models.DomainType{}
	o.QueryTable("domain_type").All(&domaintypes)
	c.Data["domaintypes"] = domaintypes

	c.Data["username"] = c.GetSession("username")
	c.TplName = "domain_add.html"
}

func (c *DomainController) AddDomain() {
	// 查询域名项目列表
	username := c.GetSession("username")
	logs.Info("session name is ", username)
	var types []models.DomainType
	o := orm.NewOrm()
	o.QueryTable("domain_type").All(&types)
	c.Data["types"] = types
	// c.Layout = "layout.html"
	c.TplName = "domain_add.html"
	name := c.GetString("domainName")
	content := c.GetString("content")
	duestr := c.GetString("duetime")
	logs.Info(name, content, duestr)
	if name == "" || content == "" || duestr == "" {
		logs.Info(" 申请域名有参数为空 重新申请")
		c.Redirect("/Domain/AddDomain", 302)
	}
	logs.Debug("duetime 数据类型：", reflect.TypeOf(duestr))
	duetimeutc, _ := time.Parse("2006-01-02", duestr)
	duetimecst, _ := time.ParseInLocation("2006-01-02", duestr, time.Local)
	logs.Debug("duetimeutc is:", duetimeutc)
	logs.Debug("duetimecst is:", duetimecst)
	// 获取项目列表
	selectedtype := c.GetString("select")
	logs.Debug("selectedtype is:", selectedtype)
	//利用此项目类型获取完整对象
	domaintype := models.DomainType{TypeName: selectedtype}
	o.Read(&domaintype, "TypeName")
	logs.Info("domaintype id is:", domaintype.Id)
	logs.Debug("domaintype 数据类型：", reflect.TypeOf(domaintype))
	//利用此 session用户 获取完整对象
	sessionname := c.GetSession("username")
	logs.Debug("sessionname is:", sessionname)

	domainuser := models.User{Id: 1}
	o.Read(&domainuser, "Id")
	logs.Debug("domainuser Id is:", domainuser.Id)
	logs.Debug("domainuser 数据类型：", reflect.TypeOf(domainuser))
	// logs.Debug("uservalue 数据类型：", reflect.TypeOf(uservalue))
	// Filter
	uservalue := sessionname.(string)
	myarroruser := []models.User{}
	myuser := models.User{}
	qs := o.QueryTable("user")
	qs.Filter("Name", uservalue).One(&myuser)
	logs.Debug("---------myuser id :", myuser.Id)
	logs.Debug("myarroruser 数据类型：", reflect.TypeOf(myarroruser))
	logs.Debug("myuser 数据类型：", reflect.TypeOf(myuser))

	domain := models.Domain{Title: name, Content: content, DueTime: duetimecst, DomainType: &domaintype, User: &myuser}
	//根据文件上传情况，判断是否更新路径
	var filename string
	uploadDir := beego.AppConfig.String("filepath")
	f, h, err := c.GetFile("uploadname")
	logs.Debug("f 数据类型：", reflect.TypeOf(f))
	logs.Debug("h 数据类型：", reflect.TypeOf(h))
	if err != nil {
		logs.Info("文件上传失败:", err)
	} else {
		/*保存之前先做校验处理:
		1.校验文件项目类型
		2.校验文件大小
		3.防止重名，重新命名
		*/
		ext := path.Ext(h.Filename)
		// logs.Info(ext)
		if ext != ".zip" && ext != ".rar" && ext != "tar*" {
			logs.Info("文件项目类型错误")
			return
		}

		if h.Size > 5000000 {
			logs.Info("文件超出大小")
			return
		}
		filename = time.Now().Format("20060102150405") + ext

		//保存文件到某路径下，程序默认当前路由的路径，故注意相对路径
		err = c.SaveToFile("uploadname", uploadDir+filename)
		if err != nil {
			logs.Info("文件保存失败：", err)
			return
		}
		defer f.Close()
	}
	//根据文件上传情况，判断是否更新路径
	if filename != "" {
		domain.File = uploadDir + filename
	}

	//插入数据库
	if name != "" && content != "" && duestr != "" {
		resint64, err := o.Insert(&domain)
		if err != nil {
			logs.Info("插入错误 err:", err)
			logs.Info("插入错误 resint64:", resint64)
			return
		}
	}

	c.Redirect("/Domain/ShowDomain", 302)
}

func (c *DomainController) DeleteDomain() {
	id, err := c.GetInt("id")
	logs.Debug("DeleteDomain 获取ID：", id)
	if err != nil {
		logs.Info("获取ID失败：", err)
		return
	}
	domain := models.Domain{Id: id}
	o := orm.NewOrm()
	o.Delete(&domain)
	c.Redirect("/Domain/ShowDomain", 302)

}

func (c *DomainController) ShowUpdateDomain() {
	/*思路
	1. 获取数据，填充数据
	2. 更新数据，更新数据库，返回列表页
	*/
	// c.Layout = "layout.html"
	c.TplName = "domain_update.html"
	id, err := c.GetInt("id")
	if err != nil {
		logs.Info("id获取失败：", err)
		return
	}
	domain := models.Domain{Id: id}
	o := orm.NewOrm()
	err = o.ReadForUpdate(&domain)
	if err != nil {
		logs.Info("读取失败：", err)
		return
	}
	c.Data["domain"] = domain
	c.Data["username"] = c.GetSession("username")
}

func (c *DomainController) UpdateDomain() {
	d, err := c.GetInt("id")
	if err != nil {
		logs.Info("id获取失败：", err)

		return
	}
	logs.Info("id获取：", d)
	title := c.GetString("title")
	content := c.GetString("content")
	duestr := c.GetString("duetime")
	logs.Info("duestr is", duestr)
	duetime, _ := time.Parse("2006-01-02", duestr)
	logs.Info("title content duetime :", title, content, duetime)
	// Read Domain对象
	o := orm.NewOrm()
	dt := models.Domain{Id: d}
	o.Read(&dt)
	// Update Domain对象
	dt.Title = title
	dt.Content = content
	dt.DueTime = duetime
	// o.Update(&dt, "Title", "Content", "DueTime")
	//根据文件上传情况，判断是否更新路径
	var filename string
	uploadDir := beego.AppConfig.String("filepath")
	f, h, err := c.GetFile("uploadname")
	logs.Debug("f 数据类型：", reflect.TypeOf(f))
	logs.Debug("h 数据类型：", reflect.TypeOf(h))
	if err != nil {
		logs.Info("文件上传失败:", err)
	} else {
		/*保存之前先做校验处理:
		1.校验文件项目类型
		2.校验文件大小
		3.防止重名，重新命名
		*/
		ext := path.Ext(h.Filename)
		// logs.Info(ext)
		if ext != ".zip" && ext != ".rar" && ext != "tar*" {
			logs.Info("文件项目类型错误")
			return
		}

		if h.Size > 5000000 {
			logs.Info("文件超出大小")
			return
		}
		filename = time.Now().Format("20060102150405") + ext

		//保存文件到某路径下，程序默认当前路由的路径，故注意相对路径
		err = c.SaveToFile("uploadname", uploadDir+filename)
		if err != nil {
			logs.Info("文件保存失败：", err)
			return
		}
		defer f.Close()
	}
	//根据文件上传情况，判断是否更新路径
	if filename != "" {
		dt.File = uploadDir + filename
	}

	o.Update(&dt)
	c.Data["message"] = "修改"
	c.TplName = ("success.html")
}

func (c *DomainController) ShowDomainDetails() {

	id, err := c.GetInt("id")
	if err != nil {
		logs.Info("获取ID失败：", err)
		return
	}
	content := models.Domain{Id: id}
	o := orm.NewOrm()
	err = o.Read(&content)
	if err != nil {
		logs.Info("查询数据失败：", err)
		return
	}
	c.Data["username"] = c.GetSession("username")
	c.Data["content"] = content
	c.TplName = ("domain_details.html")
}

func (c *DomainController) DownloadDomain() {
	url := c.GetString("url")
	logs.Info("url", url)
	c.Ctx.Output.Download(url)
}
